package 字母异位词分组;

import java.util.*;
import java.util.function.Function;

public class Solution {
    public static void main(String[] args) {

//        String[] strs = new String[]{"cab","tin","pew","duh","may","ill","buy","bar","max","doc"};
//        System.out.println(strs.length);
        String[] strs = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> lists = groupAnagrams(strs);
        System.out.println(lists.size());
        System.out.println(lists);

        for (String str : strs) {
            System.out.print(str + ",");
        }

        System.out.println("==============");
        for (String str : strs) {

            char[] chars = str.toCharArray();
            Arrays.sort(chars);

            System.out.print(String.valueOf(chars) + ",");
        }




    }
    public static List<List<String>> groupAnagrams(String[] strs) {
        List<List<String>> result = new ArrayList<>();

        Map<Integer,List<String>> map = new HashMap<>();

        for (String str : strs) {
            int charCount = 0;
            for (char c : str.toCharArray()) {
                charCount += c;
            }
            map.computeIfAbsent(charCount,m -> new ArrayList<>()).add(str);
        }

        Iterator<Map.Entry<Integer, List<String>>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            List<String> values = iterator.next().getValue();

            while(values.size() > 0) {
                List<String> tmepList = new ArrayList<>();
                String pre = null;
                Map<Character,Integer> preMap = new HashMap<>();
                Iterator<String> iterator1 = values.iterator();
                while (iterator1.hasNext()) {
                    String value = iterator1.next();
                    if (pre == null) {
                        pre = value;

                        for (char c : pre.toCharArray()) {
                            preMap.put(c, preMap.containsKey(c) ? preMap.get(c) + 1 : 1);
                        }

                        tmepList.add(pre);
                        iterator1.remove();
                    } else {
                        Map<Character, Integer> preMap2 = new HashMap<>();
                        for (char c : value.toCharArray()) {
                            preMap2.put(c, preMap2.containsKey(c) ? preMap2.get(c) + 1 : 1);
                        }
                        if (preMap2.equals(preMap)) {
                            tmepList.add(value);
                            iterator1.remove();
                        }
                    }

                }
                result.add(tmepList);
            }


        }

        return result;
    }

}
